﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frogism.Core;
namespace Frogism.Domain
{
    public class YearBugetBuilder
    {
        private DateTime Now;
        public YearBugetBuilder(DateTime current)
        {
            Now = current;
        }
        public System.Collections.Generic.IEnumerable<Frogism.Core.WeekBudgetItem> GetYearSoFar(IEnumerable<IAccount> accounts)
        {
            IEnumerable<WeekBudgetItem> weekList = YearSoFarWeekList(Now.Year);
            decimal previous = 0;

            foreach(WeekBudgetItem item in weekList){
                int totalDays = ((item.EndDate.Subtract(item.StartDate)).Days+1);
                if(totalDays == 7){
                    var week = BudgetItem.CreateWeek(item.StartDate, accounts);
                    item.Balance = week.Balance;
                }else{
                    decimal budget = BudgetItem.BudgetForDay(item.StartDate) * totalDays;
                    decimal spent = accounts.SelectMany(a => a.Transactions)
                        .Where(f => f.TransactionType.Value == Core.TransactionType.Expense.Value
                        && f.TransactionDate >= item.StartDate && f.TransactionDate <= item.EndDate
                        )
                        .Sum(r => r.Value)
                        ;
                    item.Balance = budget + spent;
                }
                item.RunningTotalStart = previous;
                previous = previous + item.Balance;
                item.RunningTotalEnd = previous;
            }
            return weekList;
        }

        private IEnumerable<WeekBudgetItem> YearSoFarWeekList(int year)
        {
            int i = 0;
            DateTime loopDate = new DateTime(year, 1, 1, 0, 0, 0);
            List<WeekBudgetItem> list = new List<WeekBudgetItem>();
            WeekBudgetItem item = new WeekBudgetItem();
            item.StartDate = loopDate;
            loopDate = loopDate.EndOfWeek();
            if (loopDate > Now)
            {
                loopDate = Now;
            }
            item.EndDate = loopDate;
            item.WeekOfYear = i++;
            list.Add(item);
            while (loopDate < Now)
            {
                loopDate = loopDate.AddDays(1);
                item = new WeekBudgetItem();
                item.StartDate = loopDate;
                loopDate = loopDate.EndOfWeek();
                if (loopDate > Now)
                {
                    loopDate = Now;
                }
                item.EndDate = loopDate;
                item.WeekOfYear = i++;
                list.Add(item);
            }

            return list;

        }
        //public IEnumerable<WeekBudgetItem> GetYearAll(int year, IEnumerable<Account> accounts)
        //{
        //}
    }
}
